package com.fg.cloud.wechar.controller.system;

import java.math.BigDecimal;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.system.vo.AgencyCartVo;
import com.fg.cloud.manager.service.agency.AgencyCartService;
import com.fg.cloud.wechar.controller.BaseWeCharController;

/**
 * Description:手机端购物车模块
 * @author dingjiang
 * @date 2017年9月30日下午2:46:56
 */
@Controller
@RequestMapping("/agencyCartWechar")
public class AgencyCartWechar extends BaseWeCharController {

	@Autowired
	private AgencyCartService agencyCartService;
	
	/**
	 * Description:手机端添加商品至购物车
	 * @param req
	 * @param resp
	 * @param sku
	 * @param amount
	 * @param unit
	 * @param stdAmount
	 * @author dingjiang
	 * @date 2017年9月6日下午4:21:06
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/insert",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void insert(HttpServletRequest request, HttpServletResponse resp, 
			AgencyCartVo entity, Long productId, Long skuId){
		//ProductSkuEntity sku, BigDecimal amount, ProductUnitEntity unit, Integer stdAmount, 
		try {
			/*Long ageId = getCurrentAgencyUser().getAgeId();
			
			//判断要添加的商品skuId和unitId是否已存在，存在就只更新数量
			if ( agencyCartService.filter(ageId, 
					entity.getSkuId(), entity.getUnitId()) ) {
				
				//判断amount是否为空
				if (null == entity.getAmount())  entity.setAmount(BigDecimal.ONE);
				
				agencyCartService.addAmount(entity.getAmount(), entity.getSkuId(), 
						entity.getUnitId(), ageId);
				doResult(resp, true, StatusCode.SAVESUCCESS, 
						agencyCartService.findCount(ageId), ResultType.SAVE_SUCCESS);
				return;
			}
			//验证参数非空
			if ( entity.getStdAmount() < 1 || null == entity.getStdAmount() ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请输入正确的换算数量");
				return ;
			}
			//判断amount是否为空
			if (null == entity.getAmount())  entity.setAmount(BigDecimal.ONE);
			
			entity.setAgeId(ageId);
			BigDecimal discount = getCurrentAgencyUser().getDiscount()
					.multiply(BigDecimal.valueOf(0.01));
			entity.setPromotionPrice(entity.getPromotionPrice().multiply(discount));
			entity.setCreator(getCurrentAgencyUser().getId());
			entity.setUpdater(getCurrentAgencyUser().getId());
			agencyCartService.insertSelective(entity);*/
		
			if (null == entity || null == skuId) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "缺少待添加购物车商品");
				return;
			}
			boolean flag = false;
			
			//将传参的skuId 设置到正确位置
			entity.setSkuId(skuId);
			entity.setId(null);
			entity.setProductId(productId);
			//将价格设置到正确位置
			//entity.setPromotionPrice(entity.getSpecialPrice());
			AgencyUserVo user = getCurrentAgencyUser();
			entity.setAgeId(user.getAgeId());
			//判断amount是否为空,若为空,数量加1
			if (null == entity.getAmount()) entity.setAmount(BigDecimal.ONE);
			//判断是否手工录入价格
			if (null == entity.getIsCustom()) entity.setIsCustom(0);
			//判断加入进来的是否是标准产品,若不是则将spec清空
			if (0 == entity.getIsStandard()) entity.setProductSpec(null);
			
			//判断要添加的商品skuId和unitId是否已存在，存在就只更新数量
			if (agencyCartService.filter(entity)) {
				flag = agencyCartService.addAmount(entity, user.getId());
				doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
						agencyCartService.findCount(user.getAgeId()), 
						flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAC_FAULT);
				return;
			}
			
			setCreateInfo(entity, request);
			setUpdateInfo(entity, request);
			entity.setFacId(user.getFacId());
			entity.setAgeId(user.getAgeId());
			flag = agencyCartService.insertSelective(entity);
			
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
					agencyCartService.findCount(user.getAgeId()), 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAC_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, 0, e.getMessage());
		}
	}
	
	/**
	 * Description:手机端查询购物车总数量
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月15日上午9:10:22
	 */
	@RequestMapping(value="/queryCount",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void queryCount(HttpServletRequest req, HttpServletResponse resp ){
		try {
			Long count = agencyCartService.findCount(getCurrentAgencyUser().getAgeId());
			if ( LongUtils.isEmpty(count) ) {
				doResult(resp, false, StatusCode.DEFAULT, 0, ResultType.FIND_NULL);
				return ;
			}
			doResult(resp, true, StatusCode.DEFAULT, count, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:手机端分页查看购物车记录
	 * @param req
	 * @param resp
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @author dingjiang
	 * @date 2017年9月6日下午4:46:41
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/baseCart",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void baseCart(HttpServletRequest req, HttpServletResponse resp, 
			Integer page, Integer rows, String sort, String order){
		try {
			if (null == page) page = 1;
			if (null == rows) rows = 10;
			PageUtils<AgencyCartVo> pageInfo = new PageUtils<AgencyCartVo>(
					page, rows, sort, order);
			AgencyUserVo CurrentUser = getCurrentAgencyUser();
			Map<String, Object> condition = pageInfo.getCondition();
			condition.put("ageId", CurrentUser.getAgeId());
			condition.put("facId", CurrentUser.getFacId());
			pageInfo.setTablename(Agency.getTableName(CurrentUser.getFacId()));
			agencyCartService.findList(pageInfo, CurrentUser);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageInfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:手机端删除购物车
	 * @param req
	 * @param resp
	 * @param ids
	 * @author dingjiang
	 * @date 2017年9月6日下午5:27:10
	 */
	@RequestMapping(value="/delete",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void delete(HttpServletRequest req, HttpServletResponse resp, String ids){
		try {
			if (StringUtils.isEmpty(ids) || ids.length() < 1) {
				doResult(resp, false, StatusCode.REMOVEERROR, null, "缺少删除项");
				return;
			}

			boolean flag = agencyCartService.deletes(getCurrentAgencyUser().getAgeId(), 
					LongUtils.convert(ids.split(",")));
			doResult(resp, flag, flag ? StatusCode.REMOVESUCCESS : StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:手机端清空购物车
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月6日下午4:55:40
	 */
	@RequestMapping(value="/empty",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void empty( HttpServletRequest req, HttpServletResponse resp ){
		try {
			
			boolean flag = agencyCartService.deleteAll(getCurrentAgencyUser().getAgeId());
			doResult(resp, flag, flag ? StatusCode.REMOVESUCCESS : StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	
	/**
	 * Description:修改商品数量
	 * @param req
	 * @param resp
	 * @param entity
	 * @author dingjiang
	 * @date 2017年8月29日下午3:01:29
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/modifyAmount",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void modifyAmount(HttpServletRequest req, HttpServletResponse resp, AgencyCartVo entity){
		try {
			//验证非空
			if ( LongUtils.isEmpty(entity.getId()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			if ( null == entity.getAmount() ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			entity.setUpdater(getCurrentAgencyUser().getId());
			agencyCartService.updateByPrimaryKeySelective(entity);
			doResult(resp, true, StatusCode.DEFAULT, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	
	/**
	 * Description:生成订单前校验
	 * @param req
	 * @param resp
	 * @param orderInfo
	 * @author dingjiang
	 * @date 2017年9月6日下午5:00:15
	 */
	/*@RequestMapping(value="/selectNew",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectNew(HttpServletRequest req, HttpServletResponse resp, OrderInfoEntity orderInfo){
		try {
			boolean stockFlag = false;
			boolean priceFlag = false;
			String stockStr = "【 ";
			String priceStr = "【 ";
			AgencyUserVo currentAgencyUser = getCurrentAgencyUser();
			BigDecimal multiply = currentAgencyUser.getDiscount().multiply(BigDecimal.valueOf(0.01));
			List<OrderDetailEntity> listDetails = orderInfo.getListDetails();
			BigDecimal totalMoney = null;
			//订单明细的库存与价格校验
			for( int i = 0; i < listDetails.size(); i++  ){
				//查询当前记录所对应的sku
				ProductSkuEntity newSku = agencyCartService.selectNewPrice(listDetails.get(i).getSkuId());
				//计算当条商品总数量
				Double totalAmount = listDetails.get(i).getAmount().doubleValue() * listDetails.get(i).getStdAmount();
				System.out.println("总数量为："+totalAmount);
				//判断该商品的库存是否充足
				if( newSku.getStock() < totalAmount && 0 == currentAgencyUser.getStockSetup().getZeroFlag() ){
					stockFlag = true;
					stockStr = stockStr.concat( ((Integer)(i+1)).toString() ).concat("."+listDetails.get(i).getProductName()+" ");	
				}
				//判断该商品价格是否有变动
				if ( !listDetails.get(i).getPromotionPrice().equals(newSku.getProductPrice().multiply(multiply)) ) {
					priceFlag = true;
					priceStr = priceStr.concat( ((Integer)(i+1)).toString() ).concat("."+listDetails.get(i).getProductName()+" ");
					listDetails.get(i).setPromotionPrice(newSku.getProductPrice().multiply(multiply));
				}	
				//统计总金额
				totalMoney = totalMoney.add(listDetails.get(i).getPromotionPrice().multiply(listDetails.get(i).getAmount()));
			}
			//这是库存不足的情况
			if ( stockFlag ) {
				doResult(resp, false, StatusCode.SAVEERROR, stockStr.concat("】"), "库存不足，无法下单！");
				return ;
			}
			//这是价格变动的情况
			if ( priceFlag ) {
				doResult(resp, false, StatusCode.SAVEERROR, priceStr.concat("】"), "商品价格已更新，订单价格异常！");
				return ;
			}
			//对订单总金额的校验
			if ( !totalMoney.equals(orderInfo.getAmountTotal()) && 1==orderInfo.getIsSpecialPrice() ) {
				orderInfo.setAmountPay(orderInfo.getSpecialPrice());
				orderInfo.setListDetails(listDetails);
				doResult(resp, true, StatusCode.SAVESUCCESS, orderInfo, ResultType.SAVE_SUCCESS);
				return ;
			}
			if ( !totalMoney.equals(orderInfo.getAmountTotal()) && 0==orderInfo.getIsSpecialPrice() ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "订单总金额有误！");
				return ;
			}
			orderInfo.setAmountPay(totalMoney);
			orderInfo.setListDetails(listDetails);
			doResult(resp, true, StatusCode.SAVESUCCESS, orderInfo, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}*/

	
}
